import { pageCuesTopic, pageCuesTopicInit } from '@/services/api/api-cues-topic';
import { parse } from '@/utils/historyUtils';
import {
  LightFilter,
  ProFormDateRangePicker,
  ProFormSelect,
  ProFormTreeSelect,
  ProList,
  ProTable,
} from '@ant-design/pro-components';
import { ActionType } from '@ant-design/pro-table';
import { Space, Tag, theme, TreeSelect } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import TableTableTopicRenderDetails from './TableTopicRenderDetails';
interface TableTopicRenderProps {
  mode: number;
  loading: boolean;
  industryIds: any[];
  actionRef?: ActionType;
  onRefurbish: () => void;
}

const TableTopicRender: React.FC<TableTopicRenderProps> = (props) => {
  const { actionRef } = props;
  const userRef = useRef<ActionType>();
  const userRefList = useRef<ActionType>();
  const access = useAccess();

  const [topicId, setTopicIdState] = useState();

  const [modeBrainOpen, setModeBrainOpenState] = useState<string>();

  const [progressCuesTopicIds, setProgressCuesTopicIdsState] = useState<string[]>([]);
  const [tableCuesTopicIds, setTableCuesTopicIdsState] = useState<string[]>([]);

  useEffect(() => {
    if (props.loading) {
      userRef.current?.reload();
      userRefList.current?.reload();
      props.onRefurbish();
    }
  }, [props.loading]);
  useEffect(() => {
    const { topicId } = parse(location.search) as { topicId: string };
    setTopicIdState(topicId);

    console.log(
      '========0000000000000================',
      topicId,
      modeBrainOpen,
      progressCuesTopicIds,
      tableCuesTopicIds,
    );

    if (!modeBrainOpen) {
      if (progressCuesTopicIds.includes(topicId)) {
        setModeBrainOpenState('progress');
      } else if (tableCuesTopicIds.includes(topicId)) {
        setModeBrainOpenState('table');
      }
    }
  }, [progressCuesTopicIds, tableCuesTopicIds]);
  /**
   * 搜索参数
   */
  const [queryParam, setQueryParamState] = useState({});

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          label: val.name,
          value: val.id,
          key: val.id,
          disabled: val.isFolder === 1 && val.isOrganization === 0 && val.children === undefined,
          children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
        });
      });
    }
    return treeData;
  }

  /**
   * 请求网络
   * @param value
   */
  const request = async (params = {}) => {
    const response = await pageCuesTopic({ pageSize: 12, current: 1, mode: props.mode, run: 1 });

    setProgressCuesTopicIdsState(response?.data?.data.map((item) => item.id));

    return Promise.resolve({
      data: response.data.data,
      total: response.data.total,
      success: response.code === 0,
    });
  };
  /**
   * 请求网络
   * @param value
   */
  const requestTable = async (params = {}, filter = {}) => {
    console.log(filter);
    const response = await pageCuesTopic({ ...params, mode: props.mode, ...queryParam });

    setTableCuesTopicIdsState(response?.data?.data.map((item) => item.id));

    return Promise.resolve({
      data: response.data.data,
      total: response.data.total,
      success: response.code === 0,
    });
  };

  /**
   * 查询单位
   */
  const [queryOrganizations, setQueryOrganizationsState] = useState<any>();

  /**
   * 申请记录
   */
  const { token } = theme.useToken();
  /**
   * 加载 页面初始化信息
   * @param key
   */
  const loadPageCuesTopicInitData = async () => {
    try {
      const response = await pageCuesTopicInit({ mode: props.mode });
      if (response.code === 0) {
        setQueryOrganizationsState(readyTreeData(response.data.queryOrganizations));
      }
    } catch (error) {}
  };
  useEffect(() => {
    loadPageCuesTopicInitData();
  }, []);

  return (
    <>
      <ProList<CuesTopicData.TopicPage>
        header={false}
        headerTitle={false}
        // ghost={false}
        // itemCardProps={{
        //   ghost: false,
        // }}
        actionRef={userRefList}
        request={request}
        showActions="hover"
        grid={{ gutter: 18, column: 4 }}
        onItem={(record: any) => {
          return {
            onMouseEnter: () => {},
            onClick: () => {},
          };
        }}
        renderItem={(item: CuesTopicData.TopicPage, index: number) => {
          return (
            <TableTableTopicRenderDetails
              topicId={topicId}
              item={item}
              onRefurbish={() => {
                userRef.current?.reload();
                userRefList.current?.reload();
              }}
              triggerMode="card"
              title={item.name}
              brainOpen={modeBrainOpen}
              brainOpenTopicMode="progress"
            />
          );
        }}
        rowKey={'id'}
        toolBarRender={false}
      />
      <ProTable<CuesTopicData.TopicPage>
        columns={[
          {
            title: '选题标题',
            key: 'name',
            dataIndex: 'name',
            width: '180px',
            search: false,
            ellipsis: true,
            render: (_, row) => (
              <>
                {row.isLinkage === 1 && (
                  <Tag color="orange">
                    {row.linkageType === 1
                      ? '协助媒体'
                      : row.linkageType === 2
                      ? '联动部门'
                      : row.linkageType === 3
                      ? '协助媒体、单位'
                      : '暂无'}
                  </Tag>
                )}
                <Tag color={row.grade === 1 ? '#f50' : row.grade === 2 ? '#ffd591' : '#2db7f5'}>
                  {row.grade === 1 ? '重大' : row.grade === 2 ? '重要' : '一般'}
                </Tag>
                <Tag color={row.run === 1 ? 'green' : row.run === 2 ? 'red' : 'orange'}>
                  {row.run === 1 ? '进行中' : row.run === 2 ? '已结束' : '已暂停'}
                </Tag>
                {row.showView === 1 && row.isView === 0 ? (
                  <Tag color="red">未阅读</Tag>
                ) : row.showSubmit === 1 && row.isSubmit === 0 ? (
                  <Tag color="red">未报送</Tag>
                ) : (
                  <></>
                )}
                <TableTableTopicRenderDetails
                  topicId={topicId}
                  item={row}
                  onRefurbish={() => {
                    userRef.current?.reload();
                    userRefList.current?.reload();
                  }}
                  triggerMode="title"
                  title={row.name}
                  brainOpen={modeBrainOpen}
                  brainOpenTopicMode="table"
                />
              </>
            ),
          },
          {
            title: '报送单位',
            dataIndex: 'createdOrganizationAvatar',
            key: 'createdOrganizationAvatar',
            width: '100px',
            valueType: 'avatar',
            render: (dom, row) => (
              <Space>
                <span>{dom}</span>
                {row.createdOrganizationName}
              </Space>
            ),
          },
          // {
          //   title: '选题方向',
          //   dataIndex: 'industryNames',
          //   width: '100px',
          //   key: 'id',
          //   render: (_, row) => {
          //     let industryNames = row?.industryNames;
          //     if (industryNames.length > 3) {
          //       industryNames = industryNames.slice(0, 3);
          //       industryNames.push('...');
          //     }
          //     return <Space size={[0, 8]} wrap>
          //       {industryNames.map((item) => (
          //         <Tag key={item}>{item}</Tag>
          //       ))}
          //     </Space>
          //   },
          // },
          // {
          //   title: '标签',
          //   dataIndex: 'labelNames',
          //   width: '100px',
          //   key: 'id',
          //   render: (_, row) => {
          //     let labelNames = row?.labelNames;
          //     if (labelNames.length > 3) {
          //       let length = labelNames.toString().length
          //       labelNames = labelNames.slice(0, 3);
          //       labelNames.push('...');
          //     }
          //     return <Space size={[0, 8]} wrap>
          //       {labelNames.map((item) => (
          //         <Tag key={item}>{item}</Tag>
          //       ))}
          //     </Space>
          //   },
          // },
          {
            title: '截止时间',
            dataIndex: 'deadlineTime',
            key: 'deadlineTime',
            width: '80px',
            align: 'center',
            valueType: 'dateTime',
          },
          {
            title: '报送线索',
            dataIndex: 'countSubmit',
            key: 'countSubmit',
            width: '50px',
            align: 'center',
            search: false,
          },
          {
            title: '报送单位',
            dataIndex: 'countSubmitOrganization',
            key: 'countSubmitOrganization',
            width: '50px',
            align: 'center',
            hideInTable: access.线索征集x配置x提供者,
            search: false,
          },
          // {
          //   title: '阅读情况',
          //   hideInSearch: true,
          //   hideInTable: access.线索征集x配置x提供者,
          //   dataIndex: 'receipt',
          //   key: 'receipt',
          //   valueType: 'avatar',
          //   width: '80px',
          //   align: 'center',
          //   search: false,
          //   render: (dom, record) => (<>
          //     <ReceiptReport id={record.id} receipt={record.receipt} onRefurbish={() => {
          //       userRef.current?.reload();
          //       userRefList.current?.reload();
          //     }} />
          //   </>),
          // },
          // {
          //   title: '数据统计',
          //   valueType: 'option',
          //   key: 'option',
          //   width: '120px',
          //   align: 'center',
          //   render: (text, record, _, action) => {
          //     if (record.recordState === 3) {
          //       if (access.线索征集x配置x提供者) {
          //         return <>
          //           <TitleText
          //             key={'title_text_count_submit_organization'}
          //             title="报送线索"
          //             text={record.countSubmit}
          //           /></>
          //       } else {
          //         return <>
          //           <TitleText
          //             key={'title_text_count_submit_organization'}
          //             title="报送单位"
          //             text={record.countSubmitOrganization}
          //           />
          //           <TitleText key={'title_text_count_submit'} title="报送线索" text={record.countSubmit} />
          //         </>
          //       }
          //     } else {
          //       return <>
          //         <Button icon={<FileTextOutlined />}>详情</Button>
          //       </>
          //     }
          //   },
          // },
        ]}
        headerTitle={false}
        ghost={true}
        pagination={{
          defaultPageSize: 9,
          showSizeChanger: false,
        }}
        search={false}
        actionRef={userRef}
        request={requestTable}
        rowKey={'id'}
        toolbar={{
          search: {
            onChange: (e) => {
              setQueryParamState({ ...queryParam, name: e.target.value });
            },
            onSearch: (value) => {
              userRef.current?.reset();
            },
          },
          filter: (
            <LightFilter
              // initialValues={{ run: 2 }}
              onValuesChange={(value) => {
                setQueryParamState(value);
                userRef.current?.reset();
              }}
            >
              <ProFormSelect
                name="grades"
                label="分类"
                mode="multiple"
                options={[
                  {
                    label: '重大',
                    value: 1,
                  },
                  {
                    label: '重要',
                    value: 2,
                  },
                  {
                    label: '一般',
                    value: 3,
                  },
                ]}
              />
              <ProFormSelect
                name="run"
                label="状态"
                options={[
                  {
                    label: '进行中',
                    value: 1,
                  },
                  {
                    label: '已结束',
                    value: 2,
                  },
                ]}
              />
              {/* <ProFormSelect
                name="industryIds"
                label="行业"
                mode="multiple"
                showSearch
                options={props.industryIds}
              /> */}
              <ProFormSelect
                hidden={!access.线索征集x配置x提供者}
                name="isView"
                label="阅读"
                options={[
                  {
                    label: '是',
                    value: 1,
                  },
                  {
                    label: '否',
                    value: 0,
                  },
                ]}
              />
              <ProFormSelect
                hidden={!access.线索征集x配置x提供者}
                name="isSubmit"
                label="报送"
                options={[
                  {
                    label: '是',
                    value: 1,
                  },
                  {
                    label: '否',
                    value: 0,
                  },
                ]}
              />
              <ProFormDateRangePicker name="deadlineTimes" label="截止范围" allowClear />

              <ProFormTreeSelect
                name="createdOrganizationIds"
                label="发布单位"
                width="xl"
                placeholder="选择单位"
                fieldProps={{
                  treeData: queryOrganizations,
                  treeCheckable: true,
                  showCheckedStrategy: TreeSelect.SHOW_PARENT,
                }}
              />
            </LightFilter>
          ),
        }}
      />
    </>
  );
};

export default TableTopicRender;
